import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { LabelManageService } from '../../../shared/services/label.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';

@Component({
  selector: 'app-label-manage',
  templateUrl: './label-manage.component.html',
  styleUrls: ['./label-manage.component.scss']
})
export class LabelManageComponent implements OnInit {

  validateForm: FormGroup;

  labelParams: any = '';
  addLabelParams: any = '';
  alertTitle: any = '';

  _value = '';
  isVisible = false;    // alert
  _allChecked = false;
  _indeterminate = false;
  _loading = false;
  _displayData = [];
  data = [];
  expandDataCache = {};

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private _modal: NzModalService,
    private _message: NzMessageService,
    private labelManageService: LabelManageService,
    private fb: FormBuilder
  ) {
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      formLayout: [ 'horizontal' ],
      materialName  : [ null, [ Validators.required ] ],
      dosageSelect  : [ null, [ Validators.required ] ],
      newLabelName : [ null ]
    });
    this.reset();
    this.getLabelList();
    this.alertAddReset();
  }

  submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
    }
  }

  get isHorizontal() {
    return this.validateForm.controls[ 'formLayout' ] && this.validateForm.controls[ 'formLayout' ].value === 'horizontal';
  }

  onSearch(event: string): void {
    // console.log(event);
    this.reset();
    this.labelParams.labelName = event;
    this.getLabelList('update');
  }

  getLabelList(type = 'create'): void {
    this.labelManageService.getLabelList(this.labelParams)
        .subscribe(res => {
          // console.log(res);
          this.labelParams.pageNumber = res['data']['pageNumber'];
          this.labelParams.totalPages = res['data']['totalPages'] * this.labelParams.pageSize;
          this.data = res['data']['list'];
          if (this._loading) {
            this._loading = false;
          }
          if (type === 'update') {
            this._message.success('数据已更新', {nzDuration: 2000});
          }
        });
  }

  reset(): void {
    this.labelParams = {
      labelName: '',
      pageSize: 10,
      pageNumber: 1,
      totalPages: 0,
    };
  }

  locationAddMaterial() {
    this.router.navigate(['./add'], {
      relativeTo: this.route
    });
  }

  delete(item) {
    // console.log(item);
    const that = this;
    const params = {
      idsName: '',
      ids: [],
    };
    if (!item) {
      params.ids = this.data.reduce((pre, next) => {
        if (next['checked']) {
          params.idsName += next['name'] + ' ,';
          pre.push(next.id);
        }
        return pre;
      }, []);
    } else {
      params.idsName = item['name'];
      params.ids.push(item['id']);
    }
    // console.log(params.ids);
    if (params.ids.length < 1) {
      return false;
    }
    this._modal.confirm({
      title  : '您是否确认要删除这些标签?',
      content: `<b>标签： ${params.idsName}</b>`,
      onOk() {
        // console.log('确定');
        that.labelManageService.postDeleteChannel(params)
            .subscribe(res => {
              // console.log(res);
              if (res['code'] === '0') {
                that._message.success('数据删除成功', {nzDuration: 2000});
                that.reset();
                that.getLabelList();
              } else {
                that._message.error('数据删除失败,' + res['msg'], {nzDuration: 4000});
              }
            });
      },
      onCancel() {
        // console.log('取消');
      }
    });
  }

  update(item): void {
    this.alertTitle = 'update';
    this.isVisible = true;
    this.alertAddReset();
    this.addLabelParams['name'] = item['name'];
    item.optionals.forEach(ele => {
      this.addLabelParams.addId++;
      this.addLabelParams['attributeList'].push({
        id: this.addLabelParams.addId,
        attributeId: ele.attributeId,
        attributeValue: ele.attributeValue
      });
    });
    this.addLabelParams.updateId = item['id'];
    // console.log('update params:', this.addLabelParams);
  }

  refresh(): void {
    this.reset();
    this.getLabelList();
    this.alertAddReset();
    this._message.success('数据已更新', {nzDuration: 2000});
  }

  // 弹窗
  showModal = () => {
    this.alertTitle = 'create';
    this.isVisible = true;
    this.alertAddReset();
  }

  handleOk = (e) => {
    let arr = [];
    arr = this.addLabelParams['attributeList'].reduce((pre, next) => {
      if (next['attributeValue']) {
        pre.push(next);
      }
      return pre;
    }, []);
    if (!this.addLabelParams.name || arr.length < 1) {
      this._message.error('标签名称和可选项都是必填的!!!', {nzDuration: 3000});
      return false;
    }
    this.addLabelParams['attributeList'] = arr;
    // console.log( this.addLabelParams);

    // 去除重名
    let reI = true;
    this.addLabelParams['attributeList'].forEach(item => {
      let itemCount = 0;
      this.addLabelParams['attributeList'].forEach(ite => {
        if (item['attributeValue'] === ite['attributeValue']) {
          itemCount++;
        }
      });
      if (itemCount > 1) {
        reI = false;
      }
    });
    if (!reI) {
      this._message.error('标签名称不能重复，请重新修改', {nzDuration: 3000});
      return false;
    }

    if (this.alertTitle === 'update') {
      this.labelManageService.postUpdateLabel(this.addLabelParams)
          .subscribe(res => {
            // console.log(res);
            if (res['code'] === '0') {
              this._message.success('标签修改成功!', {nzDuration: 2000});
              this.reset();
              this.getLabelList();
            } else {
              this._message.error('标签修改失败,' + res['msg'], {nzDuration: 4000});
            }
          });
    } else {
      this.labelManageService.postCreateLabel(this.addLabelParams)
          .subscribe(res => {
            // console.log(res);
            if (res['code'] === '0') {
              this._message.success('新增标签成功!', {nzDuration: 2000});
              this.reset();
              this.getLabelList();
            } else {
              this._message.error('新增标签失败,' + res['msg'], {nzDuration: 4000});
            }
          });
    }
    this.isVisible = false;
  }

  handleCancel = (e) => {
    // console.log(e);
    this.isVisible = false;
    this.alertAddReset();
  }

  alertAddLabel = () => {
    this.addLabelParams.addId++;
    this.addLabelParams['attributeList'].unshift({
      id: JSON.parse(JSON.stringify(this.addLabelParams.addId)),
      attributeValue: '',
    });
  }

  deleteAddLabel = (item) => {
    this.addLabelParams['attributeList'].splice(this.addLabelParams['attributeList'].findIndex(i => i['id'] === item['id']), 1);
  }

  alertAddReset = () => {
    this.addLabelParams = {
      updateId: 0,
      addId: 0,
      name: '',     // 标签名称
      attributeList: [
        // {
        //   attributeValue: ''
        // }
      ]
    };
  }

  _displayDataChange($event) {
    this._displayData = $event;
    this._refreshStatus();
  }

  _refreshStatus() {
    const allChecked = this.data.every(value => value.disabled || value.checked);
    const allUnChecked = this.data.every(value => value.disabled || !value.checked);
    this._allChecked = allChecked;
    this._indeterminate = (!allChecked) && (!allUnChecked);
  }

  _checkAll(value) {
    if (value) {
      this.data.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.data.forEach(data => data.checked = false);
    }
    this._refreshStatus();
  }

  // 分页搜索
  pageChange(reset = false) {
    if (reset) {
      this._allChecked = false;
      this._indeterminate = false;
      this.getLabelList();
    }
  }

}
